package com.study.thread.ThreadPool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class FixedThreadPoolExecutorDemo2 {
    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 30, 60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(30),Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardPolicy());

        for (int i = 0; i < 100; i++) {
//            MyTask task = new MyTask("Task " + i);
            MyTask task = new MyTask();
            /*if (i == 2) {
                try {
                //这里刻意等待task0和task1完成。
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }*/
            //线程数
            int activeCount = executor.getActiveCount();
            long taskCount = executor.getTaskCount();
            BlockingQueue queue = executor.getQueue();
            log.info("-----A new task has been added {}, activeCount={}, taskCount={}, queue={}, poolSize={}-{}",
                    "task"+i, activeCount, taskCount, queue.size(), executor.getPoolSize(), executor.getMaximumPoolSize());
            executor.execute(task);
        }
        System.out.println("Maximum threads inside pool " + executor.getMaximumPoolSize());
        executor.shutdown();
    }

    static class MyTask implements Runnable{

        @Override
        public void run() {
            try {
                Long duration = (long) (Math.random() * 10);
                //随机睡10秒内
                TimeUnit.SECONDS.sleep(duration);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
